package com.tianji.remark.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.tianji.common.utils.UserContext;
import com.tianji.remark.domain.dto.LikeRecordFormDTO;
import com.tianji.remark.domain.po.LikedRecord;
import com.tianji.remark.mapper.LikedRecordMapper;
import com.tianji.remark.service.ILikedRecordService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 点赞记录表 服务实现类
 * </p>
 *
 * @author gml
 * @since 2024-06-28
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class LikedRecordServiceImpl extends ServiceImpl<LikedRecordMapper, LikedRecord> implements ILikedRecordService {
    private final LikedRecordMapper likedRecordMapper;
    /**
     * 点赞或取消
     *
     * @param likeDTO
     */
    @Override
    public void likeOrCancel(LikeRecordFormDTO likeDTO) {
        log.info("点赞或取消，业务id：{}，业务类型：{}，是否点赞：{}", likeDTO.getBizId(), likeDTO.getBizType(), likeDTO.getLiked());
        if (ObjectUtil.isEmpty(likeDTO.getLiked()) || ObjectUtil.isEmpty(likeDTO.getBizId()) || ObjectUtil.isEmpty(likeDTO.getBizType())){
            log.error("参数错误");
        }
        //2.是否已经点赞
        if (likeDTO.getLiked()){
            List<LikedRecord> bizIdList = this.lambdaQuery()
                    .select(LikedRecord::getBizId)
                    .list();
            //2.1判断是否存在点赞记录
            if (bizIdList.contains(likeDTO.getBizId())){
                return;
            }
            //2.2点赞
            saveLikeRecord(likeDTO.getBizId(), likeDTO.getBizType());
        }else {
            //2.3取消
            cancelLike(likeDTO.getBizId());
        }
        //3.统计点赞数
        Integer likeCount = likedRecordMapper.selectCount(new LambdaQueryChainWrapper<>(likedRecordMapper)
                .eq(LikedRecord::getBizId, likeDTO.getBizId()));

        //4.使用mq发送消息给业务方


    }

    /**
     * 取消点赞
     * @param bizId
     */
    private void cancelLike(Long bizId) {
        likedRecordMapper.delete(new LambdaQueryChainWrapper<>(likedRecordMapper)
                .eq(LikedRecord::getBizId, bizId));
    }

    /**
     * 保存点赞记录
     * @param bizId
     * @param bizType
     */
    private void saveLikeRecord(Long bizId, String bizType) {
        LikedRecord likedRecord = new LikedRecord();
        likedRecord.setBizId(bizId);
        likedRecord.setBizType(bizType);
        likedRecord.setUserId(UserContext.getUser());
        this.save(likedRecord);
    }
}
